

package cn.shengchao.controler.course;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.shengchao.examstar.product.infrastructure.dao.TProductSpecificationTypeDao;
import cn.shengchao.examstar.product.infrastructure.dao.po.TProductSpecificationType;
import cn.shengchao.examstar.product.ohs.local.appservice.CourseService;
import cn.shengchao.examstar.product.ohs.local.message.CourseInfoDto;
import cn.shengchao.examstar.product.ohs.local.message.CourseListDto;
import cn.shengchao.page.PageFactory;
import cn.shengchao.service.CourseAppService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Tag(name = "课程")
@Slf4j
@RestController
@CrossOrigin("${project.cross-origin}")
@RequestMapping("/api/${project.version}/course")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private CourseAppService courseAppService;

    @Autowired
    private TProductSpecificationTypeDao tProductSpecificationTypeDao;

    @SaIgnore
    @GetMapping
    @Operation(summary = "获取课程列表", description = "获取课程列表")
    public List<CourseListDto> getCourseList(@RequestParam(required = false) String name,
                                             @RequestParam(required = false) String specifications) {
        List<Long> ids = List.of();
        if (StrUtil.isNotEmpty(specifications)) {
            ids = Arrays.stream(specifications.split(",")).map(Long::valueOf).toList();
            if (ids.isEmpty()) {
                return Collections.emptyList();
            }
            List<TProductSpecificationType> productIds = tProductSpecificationTypeDao.selectList(new LambdaQueryWrapper<TProductSpecificationType>()
                    .in(TProductSpecificationType::getSpecificationType, ids));
            if (productIds.isEmpty()) {
                return Collections.emptyList();
            }
            ids = productIds.stream().map(TProductSpecificationType::getProductId).toList();
        }
        String uid = StpUtil.getLoginId("-1");
        List<Long> finalIds = ids;
        if (uid.matches("-?\\d+(\\.\\d+)?")) {
            return PageFactory.page(() -> courseAppService.getCourseList(name, specifications, Long.valueOf(uid), finalIds));
        }
        return PageFactory.page(() -> courseAppService.getCourseList(name, specifications, -1L,finalIds));
    }

    @SaIgnore
    @GetMapping("{courseId}")
    @Operation(summary = "获取课程详情", description = "获取课程详情")
    public CourseInfoDto getCourseInfo(@PathVariable Long courseId) {
        return courseService.getCourseInfo(courseId);
    }

}
